package logrus.beanmock;

import java.lang.reflect.Method;

import logrus.beanmock.invoker.MethodInvoker;


import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class ScenarioMethodInterceptor implements MethodInterceptor {

    private final ThreadLocal<MethodInvoker> invokerHolder = new ThreadLocal<MethodInvoker>();

    public Object invoke(MethodInvocation invocation) throws Throwable {
        MethodInvoker invoker = invokerHolder.get();
        if (invoker != null) {
            Object target = invocation.getThis();
            Method method = invocation.getMethod();
            Object[] args = invocation.getArguments();
            return invoker.invoke(target, method, args);
        }
        return invocation.proceed();
    }
    
    public void setMethodInvoker(MethodInvoker methodInvoker) {
        if (invokerHolder.get() != null) {
            throw new IllegalStateException();
        }
        invokerHolder.set(methodInvoker);
    }
    
    public MethodInvoker removeMethodInvoker() {
        MethodInvoker result = invokerHolder.get();
        invokerHolder.remove();
        return result;
    }
    
}
